package com.ttpai.boot.lbs.controller;

import com.ttpai.boot.lbs.dao.BossInvitationDAO;
import com.ttpai.boot.lbs.model.BossInvitationVO;
import com.ttpai.boot.lbs.model.MetroPointVO;
import com.ttpai.boot.lbs.service.ok.MetroPointTimeService;
import com.ttpai.boot.lbs.service.ok.RealInvitationService;
import com.ttpai.boot.lbs.util.DateUtil;
import com.ttpai.boot.lbs.util.LLUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by kail on 2017/3/11.
 */
@Controller
@RequestMapping("/real")
public class RealInvitationController {

    private static final Logger logger = LoggerFactory.getLogger(RealInvitationController.class);

    @Autowired
    private BossInvitationDAO bossInvitationDAO;
    @Autowired
    private RealInvitationService invitationService;

    @Autowired
    private MetroPointTimeService metroPointTimeService;

    @RequestMapping({"/", "/index"})
    public String index() {
        return "/real/index";
    }


    // region fix_address

    @RequestMapping(value = {"/fix_address"}, method = RequestMethod.GET)
    public String fix_address(String cityName, String dateStr, Model model) {
        cityName = StringUtils.isBlank(cityName) ? "上海" : cityName;
        if (StringUtils.isNotBlank(cityName) && StringUtils.isNotBlank(dateStr)) {
            model.addAttribute("data", invitationService.selectByDateAndCity(cityName, DateUtil.format(dateStr)));
        }
        model.addAttribute("cityNames", bossInvitationDAO.selectAllCity());
        model.addAttribute("dates", new String[]{"2017-02-26", "2017-02-22", "2017-02-23", "2017-02-24", "2017-02-25", "2017-02-27", "2017-02-28", "2017-03-01", "2017-03-02", "2017-03-03", "2017-03-04", "2017-03-05"
        });
        return "/real/fix_address";
    }

    @ResponseBody
    @RequestMapping(value = {"/fix_address"}, method = RequestMethod.POST)
    public String do_fix_address(Integer auctionId, Double lng, Double lat) {
        BossInvitationVO updateVO = new BossInvitationVO();
        updateVO.setAuctionId(auctionId);
        updateVO.setLng(lng);
        updateVO.setLat(lat);
        updateVO.setHandFix(1);
        bossInvitationDAO.update(updateVO);
        return "ok";
    }
    // endregion


    // region better_metro

    /**
     * 一个点30分钟内能到达的地铁
     */
    @RequestMapping(value = {"/better_metro"}, method = RequestMethod.GET)
    public String better_metro(Model model) {
        model.addAttribute("data", invitationService.selectByDateAndCity("上海", DateUtil.format("2017-02-26")));
        return "/real/better_metro";
    }


    /**
     * 一个点30分钟内能到达的地铁
     */
    @ResponseBody
    @RequestMapping(value = {"/find_better_metro"}, method = RequestMethod.GET)
    public List<MetroPointVO> find_better_metro(Double lng, Double lat, Model model) {
        return metroPointTimeService.findNearMetro("上海", lng, lat, 60 * 30L);
    }
    // endregion

    List<List<BossInvitationVO>> linesCache = new ArrayList<>();

    /**
     *
     */
    @RequestMapping(value = {"/real_metro"}, method = RequestMethod.GET)
    public String real_metro(String cityName, String dateStr, Model model) {
        cityName = StringUtils.isBlank(cityName) ? "上海" : cityName;
        if (StringUtils.isNotBlank(cityName) && StringUtils.isBlank(dateStr)) {
        } else {
            List<BossInvitationVO> invitationVOS = invitationService.selectByDateAndCity(cityName, DateUtil.format(dateStr));
            model.addAttribute("data", invitationVOS);
            for (BossInvitationVO invitation : invitationVOS) {
                for (Integer i = 0; i < linesCache.size(); i++) {
                    List<BossInvitationVO> line = linesCache.get(i);
                    for (Integer j = 0; j < line.size(); j++) {
                        if (invitation.getAuctionId().equals(line.get(j).getAuctionId())) {
                            invitation.done = 1;
                        }
                    }
                }
            }
        }
        model.addAttribute("dates", bossInvitationDAO.selectAllCheckTime(cityName));

        model.addAttribute("linesCache", linesCache);
        model.addAttribute("cityNames", new String[]{"上海", "杭州", "南京"});


        return "/real/real_metro";
    }


    /**
     * 推荐最近的路线 和单点
     */
    @ResponseBody
    @RequestMapping(value = {"/do_real_metro_and_line"}, method = RequestMethod.POST)
    public List<List<BossInvitationVO>> do_real_metro(Double lng, Double lat, Model model) {

        List<List<BossInvitationVO>> recommendData = new ArrayList<>();

        List<BossInvitationVO> minLine = new ArrayList<>();
        Double minTime = Double.MAX_VALUE;
        for (int i = 0; i < linesCache.size(); i++) {
            List<BossInvitationVO> line = linesCache.get(i);
            if (line.size() <= 1) {
                recommendData.add(line);
                continue;
            }

            for (BossInvitationVO linePoint : line) {
                Double lineTime = LLUtil.getLinearDistance(linePoint.getLng(), linePoint.getLat(), lng, lat); // TODO 按照时间排序取最新的两条
                if (lineTime < minTime) {
                    minTime = lineTime;
                    minLine = line;
                }
            }
        }

        if (!minLine.isEmpty()) {
            recommendData.add(minLine);
        }
        return recommendData;
    }

    /**
     * 修改时间和地点
     */
    @ResponseBody
    @RequestMapping(value = {"/change_time_address"}, method = RequestMethod.POST)
    public String change_time_address(Integer auctionId, String address, String checkTimeStr, Double lng, Double
            lat) {
        BossInvitationVO curPoint = invitationService.selectCacheByAuction(auctionId);
        if (null != curPoint) {
            curPoint.setAddress(address);
            curPoint.setLat(lat);
            curPoint.setLng(lng);
            curPoint.setCheckTimeStr(checkTimeStr);
        }
        return "ok";
    }

    /**
     * 关联路线
     */
    @ResponseBody
    @RequestMapping(value = {"/do_real_line"}, method = RequestMethod.POST)
    public String do_real_line(Integer curAucId, Integer afterAucId) {
        BossInvitationVO curPoint = invitationService.selectCacheByAuction(curAucId);

        Integer lineId = null;
        Integer indexId = null;
        if ((afterAucId != null && curAucId != null) || !curAucId.equals(afterAucId)) {
            for (Integer i = 0; i < linesCache.size(); i++) {
                List<BossInvitationVO> line = linesCache.get(i);
                for (Integer j = 0; j < line.size(); j++) {
                    BossInvitationVO linePoint = line.get(j);
                    linePoint.lineIndex = i;
                    linePoint.pointIndex = j;
                    if (linePoint.getAuctionId().equals(afterAucId)) {
                        lineId = i;
                        indexId = j;
                        break;
                    }
                }
            }
        }
        if (null == lineId || null == indexId) {
            ArrayList<BossInvitationVO> objects = new ArrayList<>();
            objects.add(curPoint);
            linesCache.add(objects);
        } else {
            linesCache.get(lineId).add(indexId, curPoint);
        }
        curPoint.done = 1;
        return "ok";
    }

    @RequestMapping(value = {"/current_route"}, method = {RequestMethod.GET, RequestMethod.POST})
    public String current_route(Model model) {
        model.addAttribute("linesCache", linesCache);
        return "/real/include/current_route";
    }

    @ResponseBody
    @RequestMapping(value = {"/clear_cache"})
    public String clear_cache(Model model) {
        linesCache = new ArrayList<>();
        invitationService.cache = null;
        invitationService.selectCacheByAuction(1); // 更新缓存
        return "ok";
    }


}
